package org.ymf.task.cycle;

import javax.annotation.Resource;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.ymf.dao.PostEsDao;
import org.ymf.entity.Post;
import org.ymf.entity.PostEs;
import org.ymf.service.PostService;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 帖子 => 增量同步到 Elasticsearch
 * </p>
 *
 * @author Malphite
 * @since 2023-08-01
 */
@Slf4j
@Component
public class IncrSyncPostToEs {

    @Resource
    private PostService postService;

    @Resource
    private PostEsDao postEsDao;

    /**
     * 每分钟执行一次
     */
    @Scheduled(fixedRate = 60 * 1000)
    public void run() {
        // 查询近 5 分钟内的数据
        Date fiveMinutesAgoDate = new Date(new Date().getTime() - 5 * 60 * 1000L);
        List<Post> list = postService.list(new QueryWrapper<Post>().le("updateTime", fiveMinutesAgoDate));
        if (list.isEmpty()) return;
        List<PostEs> esList = list.stream().map(Post :: transform).collect(Collectors.toList());
        final int pageSize = 500;
        int total = esList.size();
        log.info("IncSyncPostToEs start, total {}", total);
        for (int i = 0; i < total; i += pageSize) {
            int end = Math.min(i + pageSize, total);
            log.info("sync from {} to {}", i, end);
            postEsDao.saveAll(esList.subList(i, end));
        }
        log.info("IncSyncPostToEs end, total {}", total);
    }

}
